import { defineStore } from 'pinia';
import { getToken, setToken, removeToken } from '@/utils/libs/common';
import storage from '@/utils/libs/storage';
import router from '@/router';
import { adminUserLogin, adminUserLogout, getAdminMenuAuth } from '@/utils/api/sys';
import { formatRouters } from '@/router/routes';
import { message } from 'ant-design-vue';

interface User {
    token: string,
    date: string,
    userInfo: {
        username: string,
        head_img: string,
        last_ip: string,
    },
    routers: any[],
    rules: any[]
}

const useUserStore = defineStore('user', {
    state: (): User => {
        return {
            token: getToken() || '',
            date: storage.get('login_date') || '',
            userInfo: storage.get('userinfo') || {},
            routers: [],
            rules: []
        }
    },
    actions: {
        login(form: object) {
            return new Promise((resolve, reject) => {
                adminUserLogin(form).then((res) => {
                    this.token = res.data.token;
                    this.date = res.data.date;
                    this.userInfo = res.data.user;

                    setToken(res.data.token);
                    storage.set({ key: 'userinfo', data: res.data.user });
                    storage.set({ key: 'login_date', data: res.data.date });

                    resolve(res);
                }).catch((error) => {
                    reject(error);
                })
            })
        },
        logout() {
            this.token = '';
            this.date = '';
            this.userInfo = { username: '', head_img: '', last_ip: '' };
            this.routers = [];
            this.rules = [];
            removeToken()
            storage.remove(['login_date', 'userinfo', 'routers', 'rules'])

            adminUserLogout({}).then((res: any) => {
                console.log(res)
                // message.success(res.message)
            })

            router.push('/login')
        },
        setUserInfo(data: any) {
            this.userInfo = data
            storage.set({ key: 'userinfo', data: data })
        },
        setRouters(data: any) {
            this.routers = data
            storage.set({ key: 'routers', data: data })
        },
        getAuthMenusFn() {
            return new Promise((resolve, reject) => {
                getAdminMenuAuth({}).then((res: any) => {
                    this.routers = formatRouters(res.data)
                    resolve(res)
                }).catch((error) => {
                    reject(error)
                })
            })
        },
    }
})

export default useUserStore
